<?php
/**
 * Description of UsersUI
 *
 * @author josema
 */
class UsersUI extends SystemInterface implements Actionable {

    public function serviceHandler($vars) {
        return  $this->runService($vars[0]);
    }

    protected function service_loginForm(){
        $tpl = new Template();

        $tpl->add('next_service', 'user/login');

        return $tpl->fetch('login.tpl');
    }

    protected function service_login(){
        require_once Path::getPath('users').'User.php';
        $user = new User();

        $user->formLoad();

        $dbf = new DataBaseFactory(new User);

        $dbf->selectWhere(array('*'), "email = '" . $user->email . "'");

        if($row = $dbf->fetch()){
            $db_user = new User($row);

            if(sha1($user->password) == $db_user->password){
                session_start();
                require_once Path::getPath('users').'UserManager.php';
                $manager = new UserManager();

                $manager->setCurrentUser($db_user);

                // If user login is succesfull, redirect to next service
                $interface_info = Rewrite::getInterface('transactions');
                require_once Path::getPath($interface_info['path']) . $interface_info['interface'] . '.php';

                $interface = new $interface_info['interface'];

                return $interface->runService('showAllTransactions');
            }
        }

        // If login fails
        return $this->runService('loginForm');
    }

    protected function service_register(){
        require_once Path::getPath('users').'User.php';

        $tpl = new Template();

        $tpl->add('next_service', 'user/loginForm');
        return $tpl->fetch('register.tpl');

        //return $tpl->fetch('register.tpl');


        //$user = new User();

        //$user->formLoad();

        //$user->save();
    }
}
?>
